<?php

namespace App\Api\Admin\Controllers;
use App\Models\UserActive;
use Illuminate\Support\Facades\DB;
use Illuminate\Http\Request;
use App\Models\User;
use Illuminate\Support\Carbon;
use App\Models\Shareholder;
use App\Models\MemberShip;
use App\Models\AffiliAtion;
use App\Models\RegStatistics;
use App\Models\RegistrationStatistics;
use App\Models\AppDownloads;
use Illuminate\Support\Facades\Redis;


class StatisticsController extends CommonController
{
    public function __construct()
    {
        parent::__construct();

    }
    public function OperationStatistics(Request $request)
    {
        $TotalStock = config('admin.TotalStock');//总注册资金
        $ascription = IT('ascription');
        $startdate  = IT('startdate');
        $enddate    = IT('enddate');
        $page = max(1, (int) $request->input('page'));
        $pagesize = (int) $request->input('pagesize') ?: 5;
        if(($startdate == 'Invalid date') || ($enddate =='Invalid date')){
            $startdate = '';
            $enddate = '';
        }
        $where =['status' => 0];

        $branch_office = AffiliAtion::where($where)->select('id','locality_name')->get()->toArray();
        $branch_list= [];

        foreach ($branch_office as $key) {
            $shareholder_where = ['status' => 0, 'data_audit' => 1, 'fund_audit' => 1, 'ascription' => $key['id']];
            $member_where = ['status' => 0, 'ascription' => $key['id']];
            $register_where = ['branch_office_id' => $key['id']];

            if(!empty($startdate) && !empty($enddate)){
                $Shareholder_number_Money =  Shareholder::where($shareholder_where)->whereBetween('arrival_account',[$startdate, $enddate])->sum('total_funds');
                $shareholder_shares =  Shareholder::where($shareholder_where)->whereBetween('arrival_account',[$startdate, $enddate])->sum('share');
                $Member_number_Money = MemberShip::where($member_where)->whereBetween('time_admission',[$startdate, $enddate])->sum('admission_fee');
                $shareholder_number = Shareholder::where($shareholder_where)->whereBetween('arrival_account',[$startdate, $enddate])->count();
                $memberShip_number =  MemberShip::where($member_where)->whereBetween('time_admission',[$startdate, $enddate])->count();
                $recommend = RegistrationStatistics::where($register_where)->whereBetween('created_at',[$startdate, $enddate])->count();
            }else{
                $Shareholder_number_Money =  Shareholder::where($shareholder_where)->sum('total_funds');
                $shareholder_shares =  Shareholder::where($shareholder_where)->sum('share');
                $Member_number_Money = MemberShip::where($member_where)->sum('admission_fee');
                $shareholder_number = Shareholder::where($shareholder_where)->count();
                $memberShip_number = MemberShip::where($member_where)->count();
                $recommend = RegistrationStatistics::where($register_where)->count();
            }
            $ratio =  $shareholder_shares / $TotalStock;
            $key['shareholder_number'] = $shareholder_number; // 新增股东数
            $key['memberShip_mumber'] = $memberShip_number; // 新增会员数
            $key['Totalmoney']= $Shareholder_number_Money + $Member_number_Money;   // 累积总金额
            $key['ratio']=  sprintf("%.8f", $ratio).' %'; // 认购股份总占比
            $key['recommend']= $recommend ;
            $branch_list[] =$key;
        }

        // 按总金额排序
        $total_money = array_column($branch_list,'Totalmoney');
        array_multisort($total_money,SORT_DESC,$branch_list);

        // 处理排名
        $i = 1;
        foreach($branch_list as &$statistical) {
            $statistical['sort'] = $i;
            $i++;
        }

        $list = [];
        if(!empty($ascription)){
            foreach($branch_list as $value) {
                if($value['id'] == $ascription) {
                    $list = [];
                    $list[] = $value;
                }
            }
            $total = 1;
            $totalPage = 1;
        } else {
            $total = count($branch_list);
            $totalPage = intval(ceil($total/$pagesize));
            $list = array_slice($branch_list, ($page - 1)*$pagesize, $pagesize);
        }
        return json_success('ok', ['total'=>$total,'totalPage' => $totalPage, 'list' => $list]);
    }

    public function NumberAdded( Request $request)
    {
        $ascription = IT('ascription');
        $startdate  = IT('startdate');
        $enddate    = IT('enddate');
        // 当时间为空时，取最近的上个月
        if(($startdate == 'Invalid date') || ($enddate =='Invalid date') || empty($startdate) || empty($enddate)){
            $date_list[] = [
                'start_time' => date("Y-m-01 00:00:00", strtotime("-2 month")),
                'end_time' => date('Y-m-d 23:59:59', strtotime(date('Y-m-01', strtotime("-1 month")) . ' -1 day')),
                'month' => (int)date("m", strtotime("-2 month")),
            ];
            $date_list[] = [
                'start_time' => date("Y-m-01 00:00:00", strtotime("-1 month")),
                'end_time' => date('Y-m-d 23:59:59', strtotime(date('Y-m-01') . ' -1 day')),
                'month' => (int)date("m", strtotime("-1 month")),
            ];
            $date_list[] = [
                'start_time' => date("Y-m-01 00:00:00"),
                'end_time' => date('Y-m-d H:i:s'),
                'month' => (int)date("m"),
            ];
        } else {
            $date_list = $this->handle_month_list($startdate, $enddate);
        }

        $shareholder_where = ['status' => 0, 'data_audit' => 1, 'fund_audit' => 1];
        $member_where = ['status' => 0];
        $register_where = [];
        if($ascription) {
            $shareholder_where['ascription'] = $ascription;
            $member_where['ascription'] = $ascription;
            $register_where['branch_office_id'] = $ascription;
        }

        $list = [];
        foreach($date_list as $time) {
            $data = ['month' => $time['month'].'月份'];
            $data['shareholder_number'] = Shareholder::where($shareholder_where)->whereBetween('arrival_account',[$time['start_time'], $time['end_time']])->count();
            $data['member_number'] =  MemberShip::where($member_where)->whereBetween('time_admission',[$time['start_time'], $time['end_time']])->count();
            $data['number'] = RegistrationStatistics::where($register_where)->whereBetween('created_at',[$time['start_time'], $time['end_time']])->count();
            $list[] = $data;
        }

        return json_success('ok',$list);
    }

    private function handle_month_list($start_time,$end_time){
        //转为时间戳
        $start=strtotime($start_time);
        $end=strtotime($end_time);
        $time_list = [];
        $i = 0;
        while($start<=$end){
            $firstday = strtotime('+1 month',$start) > $end ? date('Y-m-d H:i:s', $end) : date('Y-m-01', $start);
            $lastday =  strtotime('+1 month',$start) > $end ? date('Y-m-d H:i:s', strtotime($firstday)) : date('Y-m-d 23:59:59', strtotime("$firstday +1 month -1 day"));
            if($i == 0) {
                $time_list[] = ['start_time' => trim(date('Y-m-d H:i:s',$start),' '), 'end_time' => $lastday, 'month' => (int)date("m", strtotime($lastday))];
            } else {
                $time_list[] = ['start_time' => $firstday, 'end_time' => $lastday, 'month' => (int)date("m", strtotime($lastday))];
            }
            $start = strtotime('+1 month',$start);
            $i ++;
        }

        return $time_list;
    }

    /**
     * @return array
     * 钱数统计
     */
    public function AmountMoney()
    {
        $ascription = IT('ascription');
        $startdate  = IT('startdate');
        $enddate    = IT('enddate');

        if(($startdate == 'Invalid date') || ($enddate =='Invalid date') || empty($startdate) || empty($enddate)){
            $date_list[] = [
                'start_time' => date("Y-m-01 00:00:00", strtotime("-2 month")),
                'end_time' => date('Y-m-d 23:59:59', strtotime(date('Y-m-01', strtotime("-1 month")) . ' -1 day')),
                'month' => (int)date("m", strtotime("-2 month")),
            ];
            $date_list[] = [
                'start_time' => date("Y-m-01 00:00:00", strtotime("-1 month")),
                'end_time' => date('Y-m-d 23:59:59', strtotime(date('Y-m-01') . ' -1 day')),
                'month' => (int)date("m", strtotime("-1 month")),
            ];
            $date_list[] = [
                'start_time' => date("Y-m-01 00:00:00"),
                'end_time' => date('Y-m-d H:i:s'),
                'month' => (int)date("m"),
            ];
        } else {
            $date_list = $this->handle_month_list($startdate, $enddate);
        }

        $list = [];
        $shareholder_where = ['status' => 0, 'data_audit' => 1, 'fund_audit' => 1];
        $member_where = ['status' => 0];

        if($ascription) {
            $shareholder_where['ascription'] = $ascription;
            $member_where['ascription'] = $ascription;
        }
        foreach($date_list as $date) {
            $Shareholder_number_Money =  Shareholder::where($shareholder_where)->whereBetween('arrival_account',[$date['start_time'], $date['end_time']])->sum('total_funds');
            $Member_number_Money = MemberShip::where($member_where)->whereBetween('time_admission',[$date['start_time'], $date['end_time']])->sum('admission_fee');
            $data = [
                'month' => $date['month'].'月份',
                'total_funds' => $Shareholder_number_Money + $Member_number_Money,
            ];
            $list[] = $data;
        }

        return  json_success('ok',$list);
    }
    /**
     * 新增活跃用户统计
     */
    public function NewlyActive()
    {
        $today = date('Ymd', time()); // 今天
        $yesterday =  date('Ymd', strtotime('-1 day'));//昨天
        $today_user = RegStatistics::where(['day_date' => $today])->value('reg_num');
        $yesterday_user = RegStatistics::where(['day_date'=>$yesterday])->value('reg_num');
        $today_active = UserActive::where(['date_period' => $today])->count();
        $yesterday_active = UserActive::where(['date_period' => $yesterday])->count();
        $today_user_count = RegStatistics::where(['day_date' => $today])->value('total_user_num');
        $yesterday_user_count = RegStatistics::where(['day_date' => $yesterday])->value('total_user_num');
        $today_download = AppDownloads::whereDate('created_at',$today)->count();
        $yesterdaydownload = AppDownloads::whereDate('created_at',$yesterday)->count();
        $today_download_count = AppDownloads::count();
        $yesterdaydownload_count = AppDownloads::where('created_at','<',$today)->count();
        $Today_number = [
            'today_user'=> empty($today_user) ? 0 :$today_user,
            'today_active'=> empty($today_active) ? 0 : $today_active,
            'today_count'=> empty($today_user_count) ? 0 : $today_user_count,
            'today_download'=> empty($today_download) ? 0 : $today_download,
            'today_download_count'=> empty($today_download_count) ? 0 : $today_download_count,
        ];
        $yesterday_number =[
            'yesterday_user' => empty($yesterday_user) ? 0 :$yesterday_user,
            'yesterday_active' => empty($yesterday_active)? 0 :$yesterday_active,
            'yesterday_user_count' => empty($yesterday_user_count) ? 0 : $yesterday_user_count,
            'yesterdaydownload' => empty($yesterdaydownload) ? 0 : $yesterdaydownload,
            'yesterdaydownload_count' => empty($yesterdaydownload_count) ? 0 : $yesterdaydownload_count,
        ];
        return  json_success('ok',['today_number'=>$Today_number, 'yesterday_number'=>$yesterday_number]);
    }

    /**
     *新增用户日统计
     */
    public  function UserDaysStatistics()
    {
        $type =IT('type',true,'请输入类型');
        $date_list = [];
        $yesterday = strtotime(date('Y-m-d',strtotime("-1 day")));
        for ($i=1; $i<=7; $i++){
            $date['time'] = date('Ymd' ,strtotime( '+' . $i-7 .' days', $yesterday));
            $date['format_time'] = date('Y-m-d' ,strtotime( '+' . $i-7 .' days', $yesterday));
            $date['day'] =  date('Y-m-d' ,strtotime( '+' . $i-7 .' days', $yesterday));
            $date_list[] = $date;
        }

        $list = [];
        // 新增用户
        if($type == 1) {
            foreach($date_list as $date_info) {
                $data = [];
                $reg_info = RegStatistics::where(['day_date' => $date_info['time']])->first(['reg_num']);
                $data['day'] = $date_info['format_time'];
                $data['sum_mumber'] = 0;
                if($reg_info) {
                    $data['sum_mumber'] = $reg_info->reg_num;
                }
                $list[] = $data;
            }
       } elseif($type == 2) {
           // 活跃用户
           foreach($date_list as $date_info) {
               $active_count = UserActive::where(['type' => 1, 'date_period' => $date_info['time']])->count();
               $data['day'] = $date_info['format_time'];
               $data['sum_mumber'] = $active_count;
               $list[] = $data;
           }
       }

        return  json_success('ok',$list);
    }
    /**
     * @return array
     * 周统计
     */
    public  function UserWeekStatistics()
    {
        $type =IT('type',true,'请输入类型');
        $first_sunday = strtotime('-1 sunday', time());

        $date_list = [
            [
                'start_time' => date('Y-m-d 00:00:00', strtotime('-4 sunday + 1day', $first_sunday)),
                'end_time' => date('Y-m-d 23:59:59', strtotime('-3 sunday', $first_sunday)),
                'format_time' => date('Y-m-d', strtotime('-3 sunday', $first_sunday)),
                'week' => (int)date('W', strtotime('-3 sunday', $first_sunday)),
            ],
            [
                'start_time' => date('Y-m-d 00:00:00', strtotime('-3 sunday + 1day', $first_sunday)),
                'end_time' => date('Y-m-d 23:59:59', strtotime('-2 sunday', $first_sunday)),
                'format_time' => date('Y-m-d', strtotime('-2 sunday', $first_sunday)),
                'week' => (int)date('W', strtotime('-2 sunday', $first_sunday)),
            ],
            [
                'start_time' => date('Y-m-d 00:00:00', strtotime('-2 sunday + 1day', $first_sunday)),
                'end_time' => date('Y-m-d 23:59:59', strtotime('-1 sunday', $first_sunday)),
                'format_time' => date('Y-m-d', strtotime('-1 sunday', $first_sunday)),
                'week' => (int)date('W', strtotime('-1 sunday', $first_sunday)),
            ],
            [
                'start_time' => date('Y-m-d 00:00:00', strtotime('-1 sunday + 1day', $first_sunday)),
                'end_time' => date('Y-m-d 23:59:59', $first_sunday),
                'format_time' => date('Y-m-d', $first_sunday),
                'week' => (int)date('W', $first_sunday),
            ]
        ];

        $list = [];
        if($type == 1) {
            // 新增用户
            foreach($date_list as $date_info) {
                $data = [];
                $data['sum_mumber'] = RegStatistics::where(['week_date' => $date_info['week']])->sum('reg_num');
                $data['day'] = $date_info['format_time'];
                $list[] = $data;
            }
        } elseif($type == 2) {
            // 活跃用户
            foreach ($date_list as $date_info) {
                $active_count = UserActive::where(['type' => 2, 'date_period' => $date_info['week']])->count();
                $data['day'] = $date_info['format_time'];
                $data['sum_mumber'] = $active_count;
                $list[] = $data;
            }
        }

        return  json_success('ok', $list);
    }

    /**
     * @return array
     * 月统计
     */
    public  function UserMonthStatistics(){
        $type =IT('type',true,'请输入类型');
        $month_list = [];
        $last_month = strtotime(date('Y-m',strtotime("-1 month")));
        for ($i=1; $i<=3; $i++){
            $date['time'] = date('Ym' ,strtotime(  $i-3 .' month', $last_month));
            $date['format_time'] = date('Y-m' ,strtotime(  $i-3 .' month', $last_month));
            $date['day'] =  date('Y-m' ,strtotime(  $i-3 .' month', $last_month));
            $month_list[] = $date;
        }

        $list = [];
        if($type == 1) {
            // 新增用户
            foreach($month_list as $date_info) {
                $data = [];
                $data['sum_mumber'] = RegStatistics::where(['mon_date' => $date_info['time']])->sum('reg_num');
                $data['day'] = $date_info['format_time'];
                $list[] = $data;
            }
        } elseif($type == 2) {
            // 活跃用户
            foreach ($month_list as $date_info) {
                $active_count = UserActive::where(['type' => 3, 'date_period' => $date_info['time']])->count();
                $data['day'] = $date_info['format_time'];
                $data['sum_mumber'] = $active_count;
                $list[] = $data;
            }
        } elseif($type == 3) {
            // 不活跃用户
            foreach ($month_list as $date_info) {
                $active_count = UserActive::where(['type' => 99, 'date_period' => $date_info['time']])->count();
                $data['day'] = $date_info['format_time'];
                $data['sum_mumber'] = $active_count;
                $list[] = $data;
            }
        }
        return  json_success('ok',$list);
    }



    
    
    
}
